package com.example.dangerouscargodriver.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.baiju.bean.CityBean;
import com.baiju.bean.DistrictBean;
import com.baiju.bean.ProvinceBean;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.baiju.style.multipicker.MultiPickerView;
import com.baiju.style.multipicker.config.MultiPickerConfig;
import com.baiju.style.multipicker.listener.OnMultiPickerItemClickListener;
import com.baiju.style.multipicker.widget.bean.MultiItemBean;
import com.example.dangerouscargodriver.controller.AttrInfoController;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.controller.EnterPlatformInfoController;
import com.example.dangerouscargodriver.controller.UserInfoController;
import com.example.dangerouscargodriver.entry.AddressInfo;
import com.example.dangerouscargodriver.entry.ResourceTypeInfo3;
import com.example.dangerouscargodriver.entry.TruckClassInfo;
import com.example.dangerouscargodriver.entry.TruckTypeInfo;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.utils.AppManager;
import com.example.dangerouscargodriver.utils.DisplayUtil;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class EnterPlatformCompanyStepTwoActivity extends HttpRequestActivity implements View.OnClickListener {

    private static final String TAG = "EnterPlatform";

    private static final int START_ACTIVITY_FOR_COMPANY_ADDRESS  = 0;

    private ActionBar mActionBar = null;
    private EditText mCompanyName = null;
    private Button mActionCommit = null;

    //
    private ArrayList<MultiItemBean> mResourceTypeArray = null;
    private MultiPickerView mResourceTypePickerView = null;
    private LinearLayout mResourceTypeSelector = null;

    //
    private List<Integer> mSelectResource = null;

    private ArrayList<MultiItemBean> mCarTypeArray = null;
    private MultiPickerView mCarTypePickerView = null;
    private LinearLayout mCarTypeSelector = null;

    //
    private List<Integer> mSelectCar = null;

    //
    private TextView mCompanyAddress = null;

    //地址选择存储
    private ProvinceBean mSelectStartProvince = null;
    private CityBean mSelectStartCity = null;
    private DistrictBean mSelectStartDistrict = null;

    private AddressInfo mSelectAddressInfo = null;

    private EditText mCompanyAddressDetail = null;

    private EditText mContact = null;
    private EditText mTelephone = null;
    private EditText mPhone = null;

    private LinearLayout mCompanyStorageType = null;

    private ArrayList<MultiItemBean> mStorageTypeArray = null;
    private MultiPickerView mStorageTypePickerView = null;
    private LinearLayout mStorageTypeSelector = null;

    //
    private List<Integer> mSelectStorage = null;

    private HashMap<String, String> mRemotePicPath = null;
    private String mClassid = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.initHttpComponent(EnterPlatformCompanyStepTwoActivity.class);
        setContentView(R.layout.activity_enter_platform_company_step_two);
        AppManager.getAppManager().addActivity(this);

        mResourceTypeSelector = findViewById(R.id.layout_resource_type_selector);
        mResourceTypeSelector.setOnClickListener(this);

        //
        mCarTypePickerView = new MultiPickerView();
        mCarTypeArray = new ArrayList<>();
        initCarTypeInfo();
        mCarTypePickerView.init(this, mCarTypeArray);

        mCarTypeSelector = findViewById(R.id.layout_car_type_selector);
        mCarTypeSelector.setOnClickListener(this);

        //
        mSelectAddressInfo = new AddressInfo();
        mResourceTypePickerView = new MultiPickerView();
        mResourceTypeArray = new ArrayList<>();
        initResourceTypeInfo();
        mResourceTypePickerView.init(this, mResourceTypeArray);

        mCompanyAddress = findViewById(R.id.ed_company_address);
        mCompanyAddress.setOnClickListener(this);

        mCompanyAddressDetail = findViewById(R.id.ed_company_address_detail);

        mContact = findViewById(R.id.ed_contact_person);
        mTelephone = findViewById(R.id.ed_telephone_no);
        mPhone = findViewById(R.id.ed_contact_phone);

        if(getIntent().getSerializableExtra("path") != null){
            mRemotePicPath = (HashMap<String, String>) getIntent().getSerializableExtra("path");
        }
        if(getIntent().getSerializableExtra("classid") != null){
            mClassid = getIntent().getStringExtra("classid");
        }

        mCompanyName = findViewById(R.id.ed_input_company_name);
        mActionCommit = findViewById(R.id.btn_action_commit);
        mActionCommit.setOnClickListener(this);

        mCompanyStorageType = findViewById(R.id.layout_company_storage);
        if(mClassid.equals("26")){
            mCompanyStorageType.setVisibility(View.GONE);
        }
        else{
            mCompanyStorageType.setVisibility(View.VISIBLE);
        }

        mStorageTypePickerView = new MultiPickerView();
        mStorageTypeArray = new ArrayList<>();
        initStorageTypeInfo();
        mStorageTypePickerView.init(this, mStorageTypeArray);

        mStorageTypeSelector = findViewById(R.id.layout_company_storage_selector);
        mStorageTypeSelector.setOnClickListener(this);

        mActionBar = findViewById(R.id.actionEnterPlatformCompanyStepTwo);
        mActionBar.setOnBackClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void executeCommitAction(){
        HashMap<String, String> header = new HashMap<String, String>();
        header.put("token", AuthController.Instance().getToken());

        HashMap<String, String> param = new HashMap<String, String>();
        param.put("name", mCompanyName.getText().toString());
        String core_attr = "";
        for(int index = 0; index < mSelectResource.size(); index++){
            core_attr += mResourceTypeArray.get(mSelectResource.get(index)).getName() + ",";
        }
        if(core_attr.length() > 0){
            core_attr = core_attr.substring(0, core_attr.length() - 1);
        }
        param.put("core_attr", core_attr);

        String truck_class = "";
        for(int index = 0; index < mSelectCar.size(); index++){
            truck_class += mCarTypeArray.get(mSelectCar.get(index)).getId() + ",";
        }
        if(truck_class.length() > 0){
            truck_class = truck_class.substring(0, truck_class.length() - 1);
        }
        param.put("truck_class", truck_class);
        param.put("area_id", mSelectAddressInfo.getId());
        param.put("street", mCompanyAddressDetail.getText().toString());

        if(mClassid != null) {
            param.put("classid", mClassid);
        }

        if(mRemotePicPath != null) {
            param.put("cert6", mRemotePicPath.get("businessIdentify"));
            param.put("cert7", mRemotePicPath.get("businessLicense"));
            param.put("main_pic", mRemotePicPath.get("companyIdentify"));
        }
        if(mClassid.equals("69")){
            param.put("cert8", mRemotePicPath.get("chemicalsIdentify"));
            String ccfw = "";
            for(int index = 0; index < mSelectStorage.size(); index++){
                ccfw += mStorageTypeArray.get(mSelectStorage.get(index)).getId() + ",";
            }
            ccfw = ccfw.substring(0, ccfw.length() -1);
            param.put("ccfw", ccfw);
        }
        param.put("contact", mContact.getText().toString());
        param.put("mobilephone", mTelephone.getText().toString());
        if(mPhone.getText().toString() != null && !mPhone.getText().toString().equals("")){
            param.put("tel", mPhone.getText().toString());
        }
        Log.d(TAG, "param: " + param.toString());

        sendHttpFormRequest(
                RemoteAPI.REQUEST_V1_USER_COMPANY,
                header,
                param,
                RemoteAPICmd.REQUEST_V1_USER_COMPANY);
    }

    private void initResourceTypeInfo(){
        mResourceTypeArray.clear();
        List<ResourceTypeInfo3> resourceTypeArray = AttrInfoController.Instance().getResourceTypeArray3();
        if(resourceTypeArray != null && resourceTypeArray.size() > 0){
            for(int index = 0; index < resourceTypeArray.size(); index++){
                MultiItemBean bean = new MultiItemBean();
                bean.setName(resourceTypeArray.get(index).getClassname());
                bean.setId(resourceTypeArray.get(index).getClassid());
                bean.setSelected("0");
                mResourceTypeArray.add(bean);
            }
        }
        Log.d(TAG, "mResourceTypeArray: " + mResourceTypeArray.toString());
    }

    private void addResourceTypeItem(List<Integer> select){
        if(select == null){
            return;
        }

        mResourceTypeSelector.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(getBaseContext());
        for(int index = 0; index < select.size(); index++){
            View itemLayout = layoutInflater.inflate(R.layout.item_search_bar, null);

            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dp2px(getBaseContext(), 0),
                    0,
                    12,
                    0);
            itemLayout.setLayoutParams(params);

            TextView text = itemLayout.findViewById(R.id.item_show_str);
            text.setText(mResourceTypeArray.get(select.get(index)).getName());
            itemLayout.setBackgroundResource(R.drawable.rounded_button);
            mResourceTypeSelector.addView(itemLayout);
        }
    }

    private void showResourceTypeSelector(){
        MultiPickerConfig pickerConfig = new MultiPickerConfig.Builder()
                .title("选择类型")
                .build();
        pickerConfig.setTitleBackgroundColorStr("#FFD401");

        mResourceTypePickerView.setConfig(pickerConfig);
        mResourceTypePickerView.setOnMultiItemClickListener(new OnMultiPickerItemClickListener() {
            @Override
            public void onSelected(List<Integer> select) {
                super.onSelected(select);
                mSelectResource = select;
                addResourceTypeItem(select);
            }

            @Override
            public void onCancel() {
                super.onCancel();
            }
        });

        mResourceTypePickerView.showMultiPicker();
    }

    private void initCarTypeInfo(){
        mCarTypeArray.clear();
        if(AttrInfoController.Instance().getTruckTypeArray() != null &&
                AttrInfoController.Instance().getTruckTypeArray().size() > 0){
            for(int index = 0; index < AttrInfoController.Instance().getTruckTypeArray().size(); index++){
                TruckTypeInfo truckTypeInfo = AttrInfoController.Instance().getTruckTypeArray().get(index);
                List<TruckClassInfo> list = truckTypeInfo.getList();
                for(int index2 = 0; index2 < list.size(); index2++) {
                    MultiItemBean bean = new MultiItemBean();
                    bean.setName(list.get(index2).getClassname());
                    bean.setId(list.get(index2).getClassid());
                    bean.setSelected("0");
                    mCarTypeArray.add(bean);
                }
            }
        }
        Log.d(TAG, "mCarTypeArray: " + mCarTypeArray.toString());
    }

    private void addCarTypeItem(List<Integer> select){
        if(select == null){
            return;
        }

        mCarTypeSelector.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(getBaseContext());
        for(int index = 0; index < select.size(); index++){
            View itemLayout = layoutInflater.inflate(R.layout.item_search_bar, null);

            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dp2px(getBaseContext(), 0),
                    0,
                    12,
                    0);
            itemLayout.setLayoutParams(params);

            TextView text = itemLayout.findViewById(R.id.item_show_str);
            text.setText(mCarTypeArray.get(select.get(index)).getName());
            itemLayout.setBackgroundResource(R.drawable.rounded_button);
            mCarTypeSelector.addView(itemLayout);
        }
    }

    private void showCarTypeSelector(){
        MultiPickerConfig pickerConfig = new MultiPickerConfig.Builder()
                .title("选择类型")
                .build();
        pickerConfig.setTitleBackgroundColorStr("#FFD401");

        mCarTypePickerView.setConfig(pickerConfig);
        mCarTypePickerView.setOnMultiItemClickListener(new OnMultiPickerItemClickListener() {
            @Override
            public void onSelected(List<Integer> select) {
                super.onSelected(select);
                mSelectCar = select;
                addCarTypeItem(select);
            }

            @Override
            public void onCancel() {
                super.onCancel();
            }
        });

        mCarTypePickerView.showMultiPicker();
    }

    private void addStorageTypeItem(List<Integer> select){
        if(select == null){
            return;
        }

        mStorageTypeSelector.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(getBaseContext());
        for(int index = 0; index < select.size(); index++){
            View itemLayout = layoutInflater.inflate(R.layout.item_search_bar, null);

            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dp2px(getBaseContext(), 0),
                    0,
                    12,
                    0);
            itemLayout.setLayoutParams(params);

            TextView text = itemLayout.findViewById(R.id.item_show_str);
            text.setText(mStorageTypeArray.get(select.get(index)).getName());
            itemLayout.setBackgroundResource(R.drawable.rounded_button);
            mStorageTypeSelector.addView(itemLayout);
        }
    }

    private void initStorageTypeInfo(){
        MultiItemBean bean = new MultiItemBean();
        bean.setName("甲类仓库");
        bean.setId("甲类仓库");
        bean.setSelected("0");
        mStorageTypeArray.add(bean);
        MultiItemBean bean2 = new MultiItemBean();
        bean2.setName("乙类仓库");
        bean2.setId("乙类仓库");
        bean2.setSelected("0");
        mStorageTypeArray.add(bean2);
        MultiItemBean bean3 = new MultiItemBean();
        bean3.setName("丙类仓库");
        bean3.setId("丙类仓库");
        bean3.setSelected("0");
        mStorageTypeArray.add(bean3);

        Log.d(TAG, "mStorageTypeArray: " + mStorageTypeArray.toString());
    }

    private void showStorageTypeSelector(){
        MultiPickerConfig pickerConfig = new MultiPickerConfig.Builder()
                .title("选择类型")
                .build();
        pickerConfig.setTitleBackgroundColorStr("#FFD401");

        mStorageTypePickerView.setConfig(pickerConfig);
        mStorageTypePickerView.setOnMultiItemClickListener(new OnMultiPickerItemClickListener() {
            @Override
            public void onSelected(List<Integer> select) {
                super.onSelected(select);
                mSelectStorage = select;
                addStorageTypeItem(select);
            }

            @Override
            public void onCancel() {
                super.onCancel();
            }
        });

        mStorageTypePickerView.showMultiPicker();
    }

    private boolean checkInputSituation(){
        if(mCompanyName.getText().toString() == null ||
                mCompanyName.getText().toString().equals("") ||
                mContact.getText().toString() == null ||
                mContact.getText().toString().equals("") ||
                mTelephone.getText().toString() == null ||
                mTelephone.getText().toString().equals("") ||
                mSelectCar == null || mSelectCar.size() == 0 ||
                mSelectResource == null || mSelectResource.size() == 0 ||
                mSelectAddressInfo.getId().equals("") ||
                mSelectAddressInfo.getName().equals("")){
            return false;
        }
        if(mClassid.equals("69") && (mSelectStorage == null || mSelectStorage.size() == 0)){
            return false;
        }
        return true;
    }

    @Override
    protected void onHttpResponse(int actionId, String response) {
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();
            if(actionId == RemoteAPICmd.REQUEST_V1_USER_COMPANY){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    UserInfoController.Instance().updateUserInfo();
                    EnterPlatformInfoController.Instance().updateEnterStatus();
                    Intent intent = new Intent(this, EnterPlatformCompanySuccessActivity.class);
                    intent.putExtra("cid", res.getJSONObject("data").getString("cid"));
                    startActivity(intent);
                }
                else{
                    ToastUtils.showLongToast(this, res.getString("message"));
                }
            }
            else{

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHttpErrorResponse(int actionId, String response) {
        if(actionId == RemoteAPICmd.REQUEST_V1_USER_COMPANY){
            ToastUtils.showLongToast(this, "连接超时，入驻失败！");
        }
        else{
            /**/
        }
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_action_commit){
            if(checkInputSituation()) {
                executeCommitAction();
            }
            else{
                ToastUtils.showLongToast(this, "请填写完整的入驻信息！");
            }
        }
        else if(v.getId() == R.id.layout_resource_type_selector){
            showResourceTypeSelector();
        }
        else if(v.getId() == R.id.layout_car_type_selector){
            showCarTypeSelector();
        }
        else if(v.getId() == R.id.layout_company_storage_selector){
            showStorageTypeSelector();
        }
        else if(v.getId() == R.id.ed_company_address){
            Intent intent = new Intent(this, ProvinceCityDistrictPickerActivity.class);
            intent.putExtra("type", ProvinceCityDistrictPickerActivity.AREA_SELECT_DISTRICT);
            intent.putExtra("province", mSelectStartProvince);
            intent.putExtra("city", mSelectStartCity);
            intent.putExtra("district", mSelectStartDistrict);
            startActivityForResult(intent, START_ACTIVITY_FOR_COMPANY_ADDRESS);
        }
        else{

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == START_ACTIVITY_FOR_COMPANY_ADDRESS){
            if(data != null) {
                mSelectStartDistrict = (DistrictBean) data.getParcelableExtra("district");
                mSelectStartCity = (CityBean) data.getParcelableExtra("city");
                mSelectStartProvince = (ProvinceBean) data.getParcelableExtra("province");
                String select = mSelectStartProvince.getName() + " " +
                        mSelectStartCity.getName() + " " +
                        mSelectStartDistrict.getName();
                mSelectAddressInfo.setName(select);
                mSelectAddressInfo.setId("1-" + mSelectStartProvince.getId() + "-" +
                        mSelectStartCity.getId() + "-" +
                        mSelectStartDistrict.getId());
                mCompanyAddress.setText(mSelectAddressInfo.getName());
            }
        }
        else{
            /**/
        }
    }
}